package com.jiamao.goplay.ui.user.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.alibaba.fastjson.JSONArray;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResImage;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.util.GsonUtil;
import com.tamsiree.rxkit.view.RxToast;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AnonymousReportVM extends BaseViewModel<DataRepository> {

    public  int type = 0;
    public String uid;
    public AnonymousReportVM(Application application, DataRepository model) {
        super(application, model);

        MultiItemViewModel MD =  new ReportPhotoAddrItemVM(this);
        MD.multiItemType("add");
        observableListImage.add(MD);

    }

    public AnonymousReportVM.UIChangeObservable uc = new AnonymousReportVM.UIChangeObservable();
    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Integer> showPhoto = new SingleLiveEvent<>();
        public SingleLiveEvent<String> image = new SingleLiveEvent<>();

        //密码开关观察者
        public SingleLiveEvent<Boolean> showTime = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> showSex = new SingleLiveEvent<>();


        public SingleLiveEvent<EditUserPhotoItemVM> showUploadImg = new SingleLiveEvent<>();

    }

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableListImage = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBindingImage = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
            if (itemType.equals("add")){
                itemBinding.set(BR.viewModel, R.layout.report_item_add_layout);
            }else {

                itemBinding.set(BR.viewModel, R.layout.report_photo_item_layout);
            }
            //设置头布局


        }
    });


    public void uploadImage(String path,int index){
        int type = 0 ;

        File file = new File(path);
        //上传图片需要MultipartBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);

        MultipartBody.Part body = MultipartBody.Part.createFormData("File", file.getName(), requestBody);


        RequestBody param = RequestBody.create(MediaType.parse("text/plain"), type+"");


        model.getApi().uploadImage(body,param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new DisposableObserver<BaseRep<ResImage>>() {

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        //请求刷新完成收回
                        RxToast.showToastShort(throwable.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }

                    @Override
                    public void onNext(BaseRep<ResImage> o)   {
                        dismissDialog();
                        if (o.isOk()){


                            MultiItemViewModel itemPhone= new ReportPhotorItemVM(AnonymousReportVM.this,o.getData().getPath());
                            itemPhone.multiItemType("image");
                            observableListImage.add(observableListImage.size()-1,itemPhone);

                            if (observableListImage.size() >8){
                                observableListImage.remove(8);
                            }
                            //uc.image.setValue(o.getData().getPath());

                        }else {
                            RxToast.showToastShort(o.getMsg());
                        }
                    }
                });



    }



    public void sendPost(){

        ArrayList<String> stringArrayList = new ArrayList<>();
                   for (int i=0;i<observableListImage.size();i++){
                       if(observableListImage.get(i).getItemType().equals("image")) {

                           stringArrayList.add(((ReportPhotorItemVM)observableListImage.get(i)).imgUrl.get());
                       }

               }
              String pic = JSONArray.toJSONString(stringArrayList);
                 KLog.d(pic);
                model.getApi().repot(type+"",uid,pic,"")
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new DisposableObserver<BaseRep>() {

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        //请求刷新完成收回
                        RxToast.showToastShort(throwable.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }

                    @Override
                    public void onNext(BaseRep o)   {
                        dismissDialog();
                        if (o.isOk()){

                            RxToast.success(o.getMsg());
                            finish();
                            //uc.image.setValue(o.getData().getPath());

                        }else {
                            RxToast.error(o.getMsg());
                        }
                    }
                });

    }





}
